//  this library.
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hktk_app/dao/industry_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/model/industry/industry_model.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/select/select_exam_widget.dart';
import 'package:hktk_app/widget/select/select_title_widget.dart';

final IndustryModel buyModel = IndustryModel(id: "yigo", name: "已购");



/// 保存dataModel与examKey
/// 选择考试页面
class SelectExamPage extends StatefulWidget {
  final int pageIndex;

  const SelectExamPage({
    super.key,
    this.pageIndex = 0,
  });

  @override
  State<SelectExamPage> createState() => _SelectExamPageState();
}

class _SelectExamPageState extends State<SelectExamPage> {
  late BuildContext _context;

  /// 选中id
  late String _selectId;

  /// 考试名称
  late String _examName;

  /// 搜索相关key值
  late String _examSearchKey;

  /// 获取相关数据
  late List<IndustryModel> _industryList;

  /// 初始化数据放
  late Future<Map<String, dynamic>> _futureInitData;

  @override
  void initState() {
    super.initState();

    // 默认选中的id为第一个，应该是已购排在第一
    _selectId = buyModel.id!;
    _examName = buyModel.name!;
    _examSearchKey = "";
    _industryList = [];
    _futureInitData = _initIndustry();
  }

  /// 行业页面
  get _industry => Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [

          _examItems(),
          Expanded(
            child: SelectExamWidget(
              industryId: _selectId,
              industryName: _examName,
              searchKey: _examSearchKey,
              pageIndex: widget.pageIndex,
            ),
          ),
        ],
      );

  @override
  Widget build(BuildContext context) {
    _context = context;
    // 获取安全边距
    return Scaffold(
      backgroundColor: colorWhite2,
      body: SafeArea(
        child: Column(
          children: [
            SelectTitleWidget(
              pageContext: context,
              titleName: "选择考试",
              onSubmittedFun: _searchFun,
            ),
           Expanded(child:FutureBuilder<Map<String, dynamic>>(
             future: _futureInitData,
             builder: (BuildContext context, AsyncSnapshot snapshot) {
               if (snapshot.connectionState == ConnectionState.done) {
                 Map<String, dynamic> data = snapshot.data;
                 // debugPrint("返回值 ===> $data");
                 if (!data["success"]) {
                   // 执行内部的回调函数，避免跳转页面报错
                   WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
                     if (data["msg"] != null) {
                       ToastUtil.show(context: context, msg: data["msg"]);
                     }
                     // NavigatorUtil.pop(context);
                   });
                 }
                 return _industry;
               } else {
                 // 加载中
                 return const Center(
                   child: CircularProgressIndicator(),
                 );
               }
             },
           ),)
          ],
        ),
      ),
    );
  }

  /// 初始化行业方法
  Future<Map<String, dynamic>> _initIndustry() async {
    Map<String, dynamic> map = {};
    _industryList = [buyModel];
    try {
      // 设置8秒钟以后超时
      List<IndustryModel> list = await IndustryDao.getIndustry();
      _industryList.addAll(list);
      map["success"] = true;
    } catch (e) {
      map["success"] = false;
      map["msg"] = "未知错误，请重试";
      if (e is DaoException) {
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 搜索对应方法
  _searchFun(String value) {
    setState(() {
      _examSearchKey = value;
    });
  }

  /// 左边考试列表显示
  _examItems() {
    // 获取底部安全边距
    // var bottom = MediaQuery.of(_context).padding.bottom;
    var bottom = ScreenUtil().bottomBarHeight;
    return Container(
      width: 90.w,

      // height: 400,
      height: 1.sh-60-ScreenUtil().bottomBarHeight-ScreenUtil().statusBarHeight-10,
      padding: EdgeInsets.only(bottom: bottom),
      decoration: const BoxDecoration(color: colorWhite2),
      child: MediaQuery.removePadding(
        removeTop: true,
        context: _context,
        child: ListView(
          children: _industryList
              .map((IndustryModel model) => _examItem(model))
              .toList(),
        ),
      ),
    );
  }

  /// 列表item显示
  Widget _examItem(IndustryModel model) {
    String id = model.id!;
    String name = model.name!;
    return GestureDetector(
      onTap: () {
        if (_selectId != id) {
          setState(() {
            _selectId = id;
            _examName = name;
          });
        }
      },
      child: id == _selectId ? _selectItem(name) : _uncheckedItem(name),
    );
  }

  /// 选中item样式
  _selectItem(String name) {
    return Container(
      // width: 1,
      padding: EdgeInsets.only(top: 30, right: 16, bottom: 30),
      decoration: const BoxDecoration(color: colorWhite1),
      child: Row(
        children: [
          Container(
            width: 8,
            height: 38,
            decoration: const BoxDecoration(color: colorBlue1),
          ),
          Expanded(
            child: Padding(
              padding: EdgeInsets.only(left: 10),
              child: Center(
                child: Text(
                  name,
                  style: FontUtil.fontBlack1(16),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 未选中item样式
  _uncheckedItem(String name) {
    return SizedBox(
      // width: 1,
      child: Padding(
        padding: EdgeInsets.symmetric(vertical: 30, horizontal: 10),
        child: Center(
          child: Text(
            name,
            style: FontUtil.fontBlack1(16),
          ),
        ),
      ),
    );
  }
}
